package com.zlx.sharelive.activity;

import android.app.Dialog;
import android.content.Intent;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lzj.pass.dialog.PayPassDialog;
import com.lzj.pass.dialog.PayPassView;
import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.BaseBean;
import com.zlx.module_base.base_api.res_data.DynamicCommentBean;
import com.zlx.module_base.base_api.res_data.DynamicDetailBean;
import com.zlx.module_base.base_api.res_data.QueryByBean;
import com.zlx.module_base.base_api.res_data.RewardByWalletBody;
import com.zlx.module_base.base_api.res_data.UpdateUserBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_base.base_util.TimeUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.NullTokenUtils;
import com.zlx.sharelive.utils.StringUt;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 社区详情
 */
public class CommunityDetailsAc extends BaseAc {

    @BindView(R.id.iv_community_head)
    ImageView iv_community_head;
    @BindView(R.id.tv_community_nickname)
    TextView tv_community_nickname;
    @BindView(R.id.iv_community_vip)
    ImageView iv_community_vip;
    @BindView(R.id.iv_community_goddess)
    ImageView iv_community_goddess;
    @BindView(R.id.tv_community_address)
    TextView tv_community_address;
    @BindView(R.id.tv_community_time)
    TextView tv_community_time;
    @BindView(R.id.tv_community_text_title)
    TextView tv_community_text_title;
    @BindView(R.id.tv_community_text_content)
    TextView tv_community_text_content;
    @BindView(R.id.rv_community_image)
    RecyclerView rv_community_image;
    @BindView(R.id.tv_share_number)
    TextView tv_share_number;
    @BindView(R.id.tv_fabulous_number)
    TextView tv_fabulous_number;
    @BindView(R.id.tv_comment_number)
    TextView tv_comment_number;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;
    @BindView(R.id.et_text)
    EditText et_text;
    @BindView(R.id.iv_fabulous_img)
    ImageView iv_fabulous_img;
    @BindView(R.id.tv_reward_number)
    TextView tv_reward_number;

    private String touid = "";
    private String over;
    private String parentid = "";
    private String id;
    private DynamicDetailBean.InfoDTO mData;
    private List<DynamicDetailBean.InfoDTO.CmfUserDynamicsCommentsListDTO> mList = new ArrayList<>();
    private List<DynamicDetailBean.InfoDTO.CmfUserDynamicsCommentsListDTO> mList2 = new ArrayList<>();
    private CommonRecyclerViewAdapter<DynamicDetailBean.InfoDTO.CmfUserDynamicsCommentsListDTO> mAdapter;
    private List<String> mImageList = new ArrayList<>();
    private CommonRecyclerViewAdapter<String> mImageAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.ac_community_details;
    }

    @Override
    public void initViews() {
        super.initViews();

        id = getIntent().getStringExtra("id");
        parentid = id;

        getDynamicDetail();
        initRecyclerView();
        initImageRecyclerView();
        queryById();
    }

    private void initImageRecyclerView() {
        rv_community_image.setLayoutManager(new GridLayoutManager(this, 4));

        mImageAdapter = new CommonRecyclerViewAdapter<String>(this, mImageList) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, String entity, int position) {
                ImageView iv_community_image = holder.getView(R.id.iv_community_image);

                GlideImgManager.glideLoader(CommunityDetailsAc.this, entity, iv_community_image, 1);
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_community_image_layout;
            }
        };
        rv_community_image.setAdapter(mImageAdapter);
    }

    /**
     * 根据用户id查询个人信息
     */
    private void queryById() {
        ApiUtil.getLoginApi().queryById(SPUtil.getToken(this),(String) SPUtil.get(this, Constants.SP_ID, ""))
                .observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<QueryByBean>>() {
                    @Override
                    public void onSuccess(ApiResponse<QueryByBean> data) {
                        if (null != data) {
                            if (null != data.getData()) {
                                if (data.getData().getCode() == 0) {
                                    if (null != data.getData().getInfo()) {
                                        if (data.getData().getInfo().size() > 0) {
                                            if (null != data.getData().getInfo().get(0).getResult()) {
                                                if (!StringUt.isEmpty(data.getData().getInfo().get(0).getResult().getMoney())) {
                                                    over = data.getData().getInfo().get(0).getResult().getMoney();
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                                }
                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }
                }));
    }

    private void initRecyclerView() {
        rv_data.setLayoutManager(new LinearLayoutManager(this));

        mAdapter = new CommonRecyclerViewAdapter<DynamicDetailBean.InfoDTO.CmfUserDynamicsCommentsListDTO>(this, mList2) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, DynamicDetailBean.InfoDTO.CmfUserDynamicsCommentsListDTO entity, int position) {
                ImageView iv_review_head = holder.getView(R.id.iv_review_head);
                GlideImgManager.glideLoader(CommunityDetailsAc.this, entity.getAvatar(), iv_review_head, 0);
                holder.setText(R.id.tv_review_nickname, entity.getNickName());
                holder.setText(R.id.tv_review_text, entity.getContent());
                try {
                    holder.setText(R.id.tv_time, TimeUtil.getTimeStringAutoShort2(TimeUtil.ConverToDate(entity.getCreateTime()), true));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                RecyclerView rv_review = holder.getView(R.id.rv_review);
                rv_review.setLayoutManager(new LinearLayoutManager(CommunityDetailsAc.this));

                List<DynamicDetailBean.InfoDTO.CmfUserDynamicsCommentsListDTO> newList = new ArrayList<>();
                newList.clear();
                //1级评论的回复
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).getParentId().equals(entity.getId())) {
                        newList.add(mList.get(i));
                    }
                }

                for (int i = 0; i < mList.size(); i++) {
                    for (int j = 0; j < newList.size(); j++) {
                        if (mList.get(i).getParentId().equals(newList.get(j).getId())) {
                            newList.add(mList.get(i));
                        }
                    }
                }

                //2级评论的回复
                for (int i = 0; i < newList.size(); i++) {
                    for (int j = 0; j < newList.size(); j++) {
                        if (newList.get(i).getParentId().equals(newList.get(j).getId())) {
                            newList.get(i).setFlag(true);
                            newList.get(i).setName(newList.get(j).getNickName());
                        }
                    }
                }

                CommonRecyclerViewAdapter<DynamicDetailBean.InfoDTO.CmfUserDynamicsCommentsListDTO> adapter = new CommonRecyclerViewAdapter<DynamicDetailBean.InfoDTO.CmfUserDynamicsCommentsListDTO>(CommunityDetailsAc.this, newList) {
                    @Override
                    public void convert(CommonRecyclerViewHolder holder, DynamicDetailBean.InfoDTO.CmfUserDynamicsCommentsListDTO entity, int position) {
                        ImageView iv_review_head = holder.getView(R.id.iv_review_head);
                        GlideImgManager.glideLoader(CommunityDetailsAc.this, entity.getAvatar(), iv_review_head, 0);
                        holder.setText(R.id.tv_review_nickname, entity.getNickName());
                        holder.setText(R.id.tv_review_text, entity.getContent());
                        if (entity.isFlag() == true) {
                            ((LinearLayout) holder.getView(R.id.ll_reply)).setVisibility(View.VISIBLE);
                            holder.setText(R.id.tv_nickname2, entity.getName());
                        } else {
                            ((LinearLayout) holder.getView(R.id.ll_reply)).setVisibility(View.GONE);
                        }

                        try {
                            holder.setText(R.id.tv_time, TimeUtil.getTimeStringAutoShort2(TimeUtil.ConverToDate(entity.getCreateTime()), true));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public int getLayoutViewId(int viewType) {
                        return R.layout.item_review2;
                    }
                };

                rv_review.setAdapter(adapter);

                adapter.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
                    @Override
                    public void onItemClick(View v, int position) {
                        et_text.setHint("@" + newList.get(position).getNickName());
                        touid = newList.get(position).getUid();
                        parentid = newList.get(position).getId();
                    }
                });


            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_review;
            }
        };

        rv_data.setAdapter(mAdapter);


        mAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                et_text.setHint("@" + mList2.get(position).getNickName());
                touid = mList2.get(position).getUid();
                parentid = mList.get(position).getId();
            }
        });
    }

    private void getDynamicDetail() {
        ApiUtil.getServiceApi().dynamicDetail(SPUtil.getToken(this),
                id).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<DynamicDetailBean>>() {
            @Override
            public void onSuccess(ApiResponse<DynamicDetailBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            if (null != data.getData().getInfo()) {
                                if (data.getData().getInfo().size() > 0) {
                                    setDetails(data.getData().getInfo().get(0));
                                }
                            }
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }
            }
        }));
    }

    private void setDetails(DynamicDetailBean.InfoDTO data) {
        mData = data;
        GlideImgManager.glideLoader(this, data.getAvatar(), iv_community_head, 0);
        tv_community_nickname.setText(data.getNickname());
        tv_community_address.setText(data.getCity());
        tv_community_time.setText(data.getDatetime());
        tv_community_text_title.setText(data.getTitle());
        tv_share_number.setText(data.getShares());
        tv_fabulous_number.setText(data.getLikes());
        tv_comment_number.setText("(" + data.getComments() + ")");
        touid = data.getUid();
        if (data.getIsDz().equals("1")) {
            iv_fabulous_img.setImageResource(R.mipmap.fabulous_img_true);
        } else {
            iv_fabulous_img.setImageResource(R.mipmap.fabulous_img2);
        }
        tv_reward_number.setText(data.getReword());
        mList.clear();
        if (null != data) {
            if (null != data.getCmfUserDynamicsCommentsList()) {
                if (data.getCmfUserDynamicsCommentsList().size() > 0) {
                    mList.addAll(data.getCmfUserDynamicsCommentsList());
                }
            }
        }
        mList2.clear();
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).getDynamicId().equals(mList.get(i).getParentId())) {
                mList2.add(mList.get(i));
            }
        }
        mAdapter.notifyDataSetChanged();

        mImageList.clear();
        if (!StringUt.isEmpty(data.getThumbs())) {
            mImageList.add(data.getThumbs());
        }
        if (!StringUt.isEmpty(data.getThumb2())) {
            mImageList.add(data.getThumb2());
        }
        if (!StringUt.isEmpty(data.getThumb3())) {
            mImageList.add(data.getThumb3());
        }
        if (!StringUt.isEmpty(data.getThumb4())) {
            mImageList.add(data.getThumb4());
        }
        if (!StringUt.isEmpty(data.getThumb5())) {
            mImageList.add(data.getThumb5());
        }
        if (!StringUt.isEmpty(data.getThumb6())) {
            mImageList.add(data.getThumb6());
        }
        if (!StringUt.isEmpty(data.getThumb7())) {
            mImageList.add(data.getThumb7());
        }
        if (!StringUt.isEmpty(data.getThumb8())) {
            mImageList.add(data.getThumb8());
        }
        if (!StringUt.isEmpty(data.getThumb9())) {
            mImageList.add(data.getThumb9());
        }

        mImageAdapter.notifyDataSetChanged();

    }

    @OnClick({R.id.iv_back, R.id.tv_comm, R.id.ll_fabulous_img, R.id.ll_reward
            , R.id.iv_community_head})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_community_head:
                String id = (String) SPUtil.get(CommunityDetailsAc.this, Constants.SP_ID, "");
                if (id.equals(mData.getUid())) {
                    //如果是自己
                    startActivity(new Intent(CommunityDetailsAc.this, HomepageAc.class));
                } else {
                    startActivity(new Intent(CommunityDetailsAc.this, OthersHomepageAc.class)
                            .putExtra("uid", mData.getUid()));
                }
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_comm:
                if (StringUt.isEmpty(et_text.getText().toString().trim())) {
                    Toast.makeText(this, "内容不可为空", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    setComment();
                }
                break;
            case R.id.ll_fabulous_img:
                //点赞 动态
                addLike();
                break;
            case R.id.ll_reward:
                //打赏
                rewardDialog();
                break;
        }
    }

    private void rewardDialog() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_reward, null);
        dialog.setContentView(view);

        EditText et_money = view.findViewById(R.id.et_money);
//        moneyLimit(et_money);

        TextView tv_over = view.findViewById(R.id.tv_over);

        ImageView iv_close = view.findViewById(R.id.iv_close);

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        if (StringUt.isEmpty(over)) {
            tv_over.setText("￥0");
        } else {
            tv_over.setText("￥" + over);
        }

        TextView bt_play = view.findViewById(R.id.bt_play);

        bt_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!StringUt.isEmpty(et_money.getText().toString().trim()) && !StringUt.isEmpty(over)) {
                    if (Double.valueOf(over) > Double.valueOf(et_money.getText().toString().trim())) {
                        //钱够支付
                        dialogPass(et_money.getText().toString().trim());
                        dialog.dismiss();
                    } else {
                        Toast.makeText(CommunityDetailsAc.this, "余额不足", Toast.LENGTH_SHORT).show();
                    }
                } else if (StringUt.isEmpty(over)) {
                    Toast.makeText(CommunityDetailsAc.this, "余额不足", Toast.LENGTH_SHORT).show();
                }
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    private void dialogPass(String money) {
        final PayPassDialog dialog = new PayPassDialog(CommunityDetailsAc.this);
        dialog.getPayViewPass()
                .setRandomNumber(true)
                .setPayClickListener(new PayPassView.OnPayClickListener() {
                    @Override
                    public void onPassFinish(String passContent) {
                        RewardByWallet(passContent, money, dialog);
                    }

                    @Override
                    public void onPayClose() {
                        dialog.dismiss();
                        //关闭弹框
                    }

                    @Override
                    public void onPayForget() {
                        dialog.dismiss();
                        //点击忘记密码回调
                    }
                });

    }

    private void RewardByWallet(String passContent, String money, PayPassDialog dialog) {
        RewardByWalletBody rewardByWalletBody = new RewardByWalletBody();
        rewardByWalletBody.setDynamicId(id);
        rewardByWalletBody.setUid((String) SPUtil.get(this, Constants.SP_ID, ""));
        rewardByWalletBody.setToUid(mData.getUid());
        rewardByWalletBody.setMoney(money);
        rewardByWalletBody.setPassWord(passContent);
        ApiUtil.getHomeApi().RewardByWallet(SPUtil.getToken(this),
                rewardByWalletBody).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
            @Override
            public void onSuccess(ApiResponse<BaseBean> data) {
                dialog.dismiss();
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            Toast.makeText(CommunityDetailsAc.this, "打赏成功", Toast.LENGTH_SHORT).show();
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }
            }
        }));
    }

    /**
     * 点赞动态
     */
    private void addLike() {
        ApiUtil.getServiceApi().addLike(SPUtil.getToken(this),
                id,
                "2"
        ).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<UpdateUserBean>>() {
            @Override
            public void onSuccess(ApiResponse<UpdateUserBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            getDynamicDetail();
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }
            }
        }));
    }

    private void setComment() {
        DynamicCommentBean commentBean = new DynamicCommentBean();
        commentBean.setTouid(touid);
        commentBean.setDynamicid(id);
        commentBean.setParentid(parentid);
        commentBean.setContent(et_text.getText().toString().trim());
        ApiUtil.getServiceApi().setComment(SPUtil.getToken(this),
                commentBean
        ).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
            @Override
            public void onSuccess(ApiResponse<BaseBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            touid = mData.getUid();
                            parentid = id;
                            et_text.setText("");
                            et_text.setHint("发表评论，分享自己的看法");
                            getDynamicDetail();
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));
    }


    /**
     * 金钱限制
     */
    private void moneyLimit(EditText etText) {
        etText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!s.toString().matches("^(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?")) {
                    String userInput = "" + s.toString().replaceAll("[^\\d]", "");
                    StringBuilder cashAmountBuilder = new StringBuilder(userInput);

                    while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
                        cashAmountBuilder.deleteCharAt(0);
                    }
                    while (cashAmountBuilder.length() < 3) {
                        cashAmountBuilder.insert(0, '0');
                    }
                    cashAmountBuilder.insert(cashAmountBuilder.length() - 2, '.');

                    etText.setText(cashAmountBuilder.toString());
                    // keeps the cursor always to the right
                    Selection.setSelection(etText.getText(), cashAmountBuilder.toString().length());

                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }
}
